import time
import hashlib
import tarfile
import pickle
import  os
def md5(fname):#计算文件的md5值
    m = hashlib.md5()
    with open(fname,'rb') as fobj:
        while 1 :
            data = fobj.read(4096)
            if not data:
                break
            m.update(data)
    return m.hexdigest()
#完全备份
def full_backup(src,dst,md5file):#拼接文件的名字目录名＋full＋时间
    fname = '%s_full_%s.tar.gz' % (os.path.basename(src),time.strftime('%Y%m%d'))
    fname = os.path.join(dst,fname)
    #完全备份
    tar = tarfile.open(fname,'w:gz')
    tar.add(src)
    tar.close()
    #计算所有文件的md5值
    md5dic = {}
    for path,folders,files in os.walk(src):
        for file in files:
            key = os.path.join(path,file)
            md5dic[key] = md5(key)
    #以｛'文件名'：'md5值'｝存放
    with open(md5file,'wb') as fobj:
        pickle.dump(md5dic,fobj)
#增量备份
def incr_backup(src,dst,md5file):
    # 拼接文件的名字目录名＋incr＋时间
    fname = '%s_incr_%s.tar.gz' % (os.path.basename(src),time.strftime('%Y%m%d'))
    fname = os.path.join(dst,fname)
    # 计算所有文件的md5值
    md5dict = {}
    for path,folders,files in os.walk(src):
        for file in files:
            key = os.path.join(path,file)
            md5dict[key] = md5(key)
    #取出上次备份的md5值
    with open(md5file,'rb') as fobj:
        old_md5 = pickle.load(fobj)
    #将新的md5值和旧的md5值比较
    tar = tarfile.open(fname,'w:gz')
    for key in md5dict:
        if old_md5.get(key) !=md5dict[key]:
            tar.add(key)
    tar.close()
    #保存md5值
    with open(md5file,'wb') as fobj:
        pickle.dump(md5dict,fobj)

if __name__ == '__main__':
    src = '/opt/security' #需要备份的文件或目录
    dst = '/opt'#备份到的目录
    md5file = '/opt/md5file'#存放md5值的文件
    if time.strftime('%a') == 'Mon':
        full_backup(src,dst,md5file)
    else:
        incr_backup(src,dst,md5file)
